package Admin

import (
	"fmt"
	"net/http"
	"strconv"

	"github.com/duke-git/lancet/v2/maputil"
	"github.com/gin-gonic/gin"
	"github.com/spf13/cast"

	"hyper/app/Http/Controllers"
	"hyper/app/Models"
	"hyper/app/Requests/Admin"
	"hyper/supports/auth"
	"hyper/supports/jwt"
	"hyper/supports/redis"
	"hyper/supports/response"
	"hyper/supports/validators"
)

type LoginController struct {
	Controllers.BaseController
}

// 用户注册
func (l *LoginController) Register(c *gin.Context) {

	// 语系
	lang := c.GetHeader("Accept-Language")

	// 参数
	param, pex := c.Get("params")
	if !pex {
		response.ResponseException(c, http.StatusOK, "解密失败", nil)
		return
	}

	// map 转结构体
	var data Admin.RegisterRequest
	err := maputil.MapTo(param, &data)
	if err != nil {
		response.ResponseException(c, http.StatusOK, err.Error(), nil)
		return
	}

	// 验证器
	if err = validators.NewComValidator(data, lang); err != nil {
		response.ResponseException(c, http.StatusUnprocessableEntity, err.Error(), nil)
		return
	}

	_user := Models.User{
		UserName:   data.UserName,
		Email:      data.Email,
		Password:   data.Password,
		Phone:      data.Phone,
		RealName:   data.RealName,
		IsBan:      0,
		Status:     1,
		RegisterIp: c.ClientIP(),
	}

	_user.Create()

	if _user.ID > 0 {
		response.ResponseException(c, http.StatusOK, "注册成功！", nil)
		return
	} else {
		response.ResponseException(c, http.StatusContinue, "注册失败，请联系管理员", nil)
		return
	}

}

// 用户登录

func (l *LoginController) Login(c *gin.Context) {

	// r := Admin.LoginRequest{}
	// if ok := request.FormDataValidation(c, &r, Admin.ValidateAdminLoginRequest); !ok {
	// 	return
	// }
	username := c.PostForm("username")
	password := c.PostForm("password")

	// 尝试登录
	_user, err := auth.Attempt(username, password)

	if err != nil {
		response.ResponseException(c, http.StatusContinue, err.Error(), nil)
		return
	}

	if _user.IsBan == 1 || _user.Status != 1 {
		response.ResponseException(c, http.StatusContinue, "該帳號异常，請聯系管理員！", nil)
		return
	}

	_admin := response.D{
		"id":          _user.ID,
		"username":    _user.UserName,
		"email":       _user.Email,
		"phone":       _user.Phone,
		"role_id":     1,
		"real_name":   _user.RealName,
		"status":      _user.Status,
		"register_ip": _user.RegisterIp,
		"created_at":  _user.CreatedAt,
		"updated_at":  _user.UpdatedAt,
	}

	token, _ := jwt.CreateToken(_admin, fmt.Sprintf("user_%s", strconv.FormatUint(_user.ID, 10)))

	response.ResponseException(c, http.StatusOK, "登录成功！", response.D{
		"token": token,
		"user":  _admin,
	})
}

// 用户信息
func (l *LoginController) Me(c *gin.Context) {
	user, _ := auth.Auth("", c)
	response.ResponseException(c, http.StatusOK, "Success", user)
	return
}

// 用户退出
func (l *LoginController) Logout(c *gin.Context) {
	strToken, _ := jwt.GetTokenFromHeader(c)
	id, _ := auth.Auth("id", c)

	if jwt.AddTokenToBlacklist(strToken) {
		fmt.Println(redis.Redis.Delete(fmt.Sprintf("user_%s", cast.ToString(id))))
		response.ResponseException(c, http.StatusOK, "退出成功", nil)
		return
	} else {
		response.ResponseException(c, http.StatusContinue, "退出失败！", nil)
		return
	}
}
